package com.permission.util;

import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import org.codehaus.jackson.type.TypeReference;

import lombok.extern.slf4j.Slf4j;

/**
 * json处理工具
 * @author jing
 *
 */
@Slf4j
public class JsonMapper {
	
	//全局的Object处理
	private static ObjectMapper objectMapper = new ObjectMapper();
	
	static{
		// config
        objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
        objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
	}
	
	//将对象转换为字符串
	public static <T> String objToString(T t){
			if(t == null){
				return null;
			}
			try {
				//如果是字符串的话直接返回，否则转化为字符串
				return t instanceof String ? (String)t: objectMapper.writeValueAsString(t);
			} catch (Exception e) {
				/*
				 * 这里没有跑出异常的原因是因为如果对象不为空的时候
				 * 我们还要转化为空的话，调用端就会知道这边出错了
				 */
				log.warn("parse Object to String exception",e);
				return null;
			}
	}
	
	//将字符串转化为对象
	public static <T> T stringToObject(String str,TypeReference<T> tr){
		if(str == null || tr == null){
			return null; 
		}
		try {
			//如果传入的参数是String类型的话直接返回String，否则转化为“T”类型
            return (T) (tr.getType().equals(String.class) ? str : objectMapper.readValue(str, tr));
        } catch (Exception e) {
            log.warn("parse String to Object exception, String:{}, TypeReference<T>:{}, error:{}", str, tr.getType(), e);
            return null;
        }
	}
}
